import json

from PyQt6 import uic
from PyQt6.QtCore import QSize, Qt
from PyQt6.QtGui import QIcon, QPixmap
from PyQt6.QtWidgets import QWidget, QToolButton, QSplitter, QGridLayout, QMessageBox, QListWidgetItem, QLabel, \
    QSizePolicy, QVBoxLayout, QHBoxLayout

from utils.index import resource_path
from front.components.historyListDel import Window as HistoryListDel
from utils.showImage import load_hd_pixmap


class Window(QWidget):
    def __init__(self, path, joint_well):
        super().__init__()
        self.image_label = None  # 展示出图结果的标签控件
        self.path = path  # 存放历史记录文件的路径
        self.data = None  # 读取到的联井标定历史记录
        self.joint_well = joint_well  # 联井标定页面的对象
        self.module_name = "联井标定"
        self.e_name = "joint_well"
        self.ui = uic.loadUi(resource_path("static/ui/historyJointWell.ui"), self)  # 加载 UI 文件
        self.init_style()  # 初始化页面样式，页面内容
        self.init_event()

    # ========================================================
    # 重写方法
    # ========================================================
    # 根据窗口宽度动态调整

    def resizeEvent(self, event):
        # 获取窗口当前宽度
        width = self.width()
        # 根据窗口宽度动态调整字体大小
        fontSize = int(width / 150)
        if fontSize < 10:
            fontSize = 10
        if fontSize > 18:
            fontSize = 18

        # 定义一个递归函数来遍历所有子控件，并设置字体大小
        def traverse_widgets(widget):
            if hasattr(widget, 'setFont'):
                font = widget.font()
                font.setPointSize(fontSize)
                widget.setFont(font)
            for child in widget.children():
                traverse_widgets(child)

        # 从主窗口开始遍历所有控件
        traverse_widgets(self)

        # 显示的图片
        image_width = int(width / 3 * 2)
        image_height = int(image_width / 53 * 58)
        if image_width < 800:
            image_width = 800
        if image_height < 875:
            image_height = 875
        self.ui.widget.setFixedSize(image_width, image_height)

        # 设置ToolButton的大小
        buttons = self.findChildren(QToolButton)
        for btn in buttons:
            icon_size = int(width / 100)
            btn.setIconSize(QSize(icon_size, icon_size))

        super().resizeEvent(event)

    # 重写 keyPressEvent 方法，按下左右按键可以控制listWeight选项，左箭头选项上移，右箭头选项下移
    def keyPressEvent(self, event):
        if event.key() == Qt.Key.Key_Left:
            count = len(self.data)
            index = self.ui.listWidget.currentRow()
            index = index - 1
            if index < 0:
                index = count - 1
            self.init_detail(self.data[index], index + 1)
            self.ui.listWidget.setCurrentRow(index)
        elif event.key() == Qt.Key.Key_Right:
            count = len(self.data)
            index = self.ui.listWidget.currentRow()
            index = index + 1
            if index >= count:
                index = 0
            self.init_detail(self.data[index], index + 1)
            self.ui.listWidget.setCurrentRow(index)
        super().keyPressEvent(event)  # 调用父类的 keyPressEvent 处理其他按键

    # ========================================================
    # 初始化页面
    # ========================================================

    def init_style(self):
        self.ui.setWindowTitle("SeismicPlot-联井标定历史记录")
        self.ui.setWindowIcon(QIcon(resource_path('static/image/favicon.ico')))
        self.ui.scrollArea.setStyleSheet("background-color: white;")

        # 设置布局
        line = self.ui.line
        line.setParent(None)
        # 创建 QSplitter
        splitter = QSplitter()
        # 获取 listWidget 和 scrollArea
        list_widget = self.ui.listWidget
        scroll_area = self.ui.scrollArea
        # 将 listWidget 和 scrollArea 添加到 QSplitter 中
        splitter.addWidget(list_widget)
        splitter.addWidget(scroll_area)
        sizes = [300, 900]
        splitter.setSizes(sizes)
        # 将 QSplitter 添加到主布局
        grid_layout = QGridLayout()
        grid_layout.addWidget(splitter, 0, 0)
        self.setLayout(grid_layout)

        # 设置图标
        self.ui.toolButton.setIcon(QIcon(resource_path('static/image/load.png')))  # 导入
        self.ui.toolButton_2.setIcon(QIcon(resource_path('static/image/del.png')))  # 删除
        self.ui.toolButton_3.setIcon(QIcon(resource_path('static/image/dels.png')))  # 批量删除

        self.init_content()

    # 初始化页面的内容，创建页面元素，并填充内容
    def init_content(self):
        list_widget = self.ui.listWidget
        list_widget.clear()  # 删除 QListWidget 中的所有选项

        with open(self.path, 'r', encoding='utf-8') as file:
            history_data = json.load(file)
            joint_well_history_data = history_data["joint_well"]
            if len(joint_well_history_data) == 0:
                QMessageBox.critical(self, 'SeismicPlot-联井标定历史记录', '暂无历史记录',
                                     QMessageBox.StandardButton.Ok)
                self.ui.close()
                return
            self.data = joint_well_history_data
            for i in range(len(joint_well_history_data)):
                item_data = joint_well_history_data[i]
                item = QListWidgetItem(f"{i + 1} {item_data['title']} {item_data['date_time']}")
                if item_data["status"] == "success":
                    item.setIcon(QIcon(resource_path('static/image/success.png')))
                else:
                    item.setIcon(QIcon(resource_path('static/image/error.png')))
                list_widget.addItem(item)

        list_widget.setCurrentRow(0)  # 默认选中第一个的数据项

        self.init_detail(joint_well_history_data[0], 1)

    # 初始化参数的具体内容，datas为历史记录文件中的joint_well中的当前的数据项，index为数据项的下标
    def init_detail(self, datas, index):
        # 头部基本信息
        self.ui.label_94.setText(f"{index}")
        self.ui.label.setText(f"{datas['title']}")  # 标题
        self.ui.label_2.setText(f"{datas['date_time']}")  # 日期时间

        data = datas["data"]
        # 输出文件
        self.ui.label_6.setText(f"{data['outfile']}")  # 文件名
        # 输出文件图片
        if self.image_label is not None:  # 还未设置label标签
            pixmap = load_hd_pixmap(self, data['outfile'])
            if pixmap.isNull():
                pixmap = load_hd_pixmap(resource_path(resource_path("static/image/no-image.png")))
            self.image_label.setPixmap(pixmap)
        else:
            self.image_label = QLabel()
            pixmap = load_hd_pixmap(self, data['outfile'])
            if pixmap.isNull():
                pixmap = load_hd_pixmap(self, resource_path(resource_path("static/image/no-image.png")))
            self.image_label.setPixmap(pixmap)
            # 保持宽高比并平滑缩放
            self.image_label.setScaledContents(True)
            self.image_label.setSizePolicy(
                QSizePolicy.Policy.Expanding,
                QSizePolicy.Policy.Expanding
            )
            layout = QVBoxLayout()
            layout.addWidget(self.image_label)
            self.ui.widget.setLayout(layout)
        # 地面文件
        label1 = QLabel()
        label1.setText("地面文件")
        self.ui.verticalLayout.addWidget(label1)
        self.add_elem("文件", data['seisdata'])  # 文件名
        self.add_elem("时间绘制范围", f"{data['trange'][0]}~{data['trange'][1]}s")  # 时间绘制范围
        # well
        for i in range(data['wellnum']):
            label1 = QLabel()
            label1.setText(f"well{i + 1}")
            self.ui.verticalLayout.addWidget(label1)
            self.add_elem("井名", data[f'wellname{i + 1}'])  # 井名
            self.add_elem("井数据", data[f'welldata{i + 1}'])  # 井数据
            self.add_elem("井层位标定表", data[f'wellfc{i + 1}'])  # 井层位标定表
            self.add_elem("wellts", data[f'wellts{i + 1}'])  # wellts
            self.add_elem("welllrnum", data[f'welllrnum{i + 1}'])  # welllrnum
            self.add_elem("wellstep", data[f'wellstep{i + 1}'])  # wellstep
        # 设置
        label1 = QLabel()
        label1.setText("设置")
        self.add_elem("深度比例尺", data["tpi"])  # 深度比例尺
        self.add_elem("时间比例尺", data["ips"])  # 时间比例尺
        self.add_elem("增益时窗", data["agc"])  # 增益时窗
        self.add_elem("分层线长度", data["fcxc"])  # 分层线长度
        self.add_elem("rgb", f"{data['colour'][0]}, {data['colour'][1]}, {data['colour'][2]}")  # rgb
        self.add_elem("opacity", data["opacity"])  # opacity
        self.add_elem("lineweight", data["lineweight"])  # lineweight
        self.add_elem("fontsize", data["fontsize"])  # fontsize

    def add_elem(self, label, val):
        label2 = QLabel()
        label2.setText(f"  - {label}:")
        label3 = QLabel()
        label3.setText(f"{val}")
        horizontal_layout = QHBoxLayout()
        horizontal_layout.addWidget(label2)
        horizontal_layout.addWidget(label3)
        horizontal_layout.setContentsMargins(0, 0, 0, 0)  # 去除容器内部边距
        horizontal_layout.setStretch(0, 0)  # 设置伸缩比例
        horizontal_layout.setStretch(1, 1)
        container_3 = QWidget()
        container_3.setLayout(horizontal_layout)
        self.ui.verticalLayout.addWidget(container_3)

    # ========================================================
    # 初始化事件
    # ========================================================
    def init_event(self):
        self.ui.listWidget.itemClicked.connect(self.list_item_clicked)  # 列表项
        self.ui.toolButton.clicked.connect(self.load_item)  # 导入
        self.ui.toolButton_2.clicked.connect(self.del_item)  # 删除
        self.ui.toolButton_3.clicked.connect(self.del_items)  # 批量删除


    # 处理列表项被点击的事件
    def list_item_clicked(self):
        index = self.ui.listWidget.currentRow()
        self.init_detail(self.data[index], index + 1)

    # 将当前的历史记录项导入
    def load_item(self):
        index = int(self.ui.label_94.text()) - 1
        result = QMessageBox.question(self, 'SeismicPlot-联井标定历史记录',
                                      f'确认导入[第{index + 1}项|{self.data[index]["title"]}]？',
                                      QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Apply | QMessageBox.StandardButton.Cancel)
        if result == QMessageBox.StandardButton.Ok:
            self.joint_well.load_params(self.data[index])  # 将数据导入joint_well页面
            self.ui.close()  # 关闭historyMulWave页面
        elif result == QMessageBox.StandardButton.Apply:
            self.joint_well.load_params(self.data[index])  # 将数据导入joint_well页面
        elif result == QMessageBox.StandardButton.Cancel:
            pass

    # 将当前历史记录删除
    def del_item(self):
        index = int(self.ui.label_94.text()) - 1
        result = QMessageBox.question(self, 'SeismicPlot-联井标定历史记录',
                                      f'确认删除[第{index + 1}项|{self.data[index]["title"]}]？',
                                      QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Apply | QMessageBox.StandardButton.Cancel)
        if result == QMessageBox.StandardButton.Ok:
            # 读取历史记录文件
            with open(self.path, 'r', encoding='utf-8') as file:
                history_data = json.load(file)
                joint_well_history_data = history_data.get("joint_well", [])
            # 删除数据
            joint_well_history_data.pop(index)  # 删除self.data中的第index项
            # 关闭historyMulWave页面
            self.ui.close()
            # 历史记录文件重新写入数据
            with open(self.path, 'w', encoding='utf-8') as file:
                json.dump(history_data, file, indent=4)
            # 重新加载页面内容
            self.init_content()
        elif result == QMessageBox.StandardButton.Apply:
            # 读取历史记录文件
            with open(self.path, 'r', encoding='utf-8') as file:
                history_data = json.load(file)
                joint_well_history_data = history_data.get("joint_well", [])
            # 删除数据
            joint_well_history_data.pop(index)  # 删除self.data中的第index项
            # 历史记录文件重新写入数据
            with open(self.path, 'w', encoding='utf-8') as file:
                json.dump(history_data, file, indent=4)
            # 重新加载页面内容
            self.init_content()
        elif result == QMessageBox.StandardButton.Cancel:
            pass

    # 批量删除历史记录
    def del_items(self):
        self.ui.history_list_del_ui = HistoryListDel(self.path, self)
        self.ui.history_list_del_ui.show()